package temp.lho.lws.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import temp.lho.lws.pojo.TbRole;
import temp.lho.lws.service.ILoginService;
import temp.lho.lws.vo.LoginVo;

import java.util.HashSet;
import java.util.List;

/**
 * 自定义Realm
 *
 * @author x1c
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ILoginService loginService;

    // 用来做认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取身份信息
        String principal = (String) token.getPrincipal();
        //从数据库查询用户
        LoginVo login = loginService.login(principal);
        if (login != null) {
            return new SimpleAuthenticationInfo(
                    login,
                    login.getPassword(),
                    ByteSource.Util.bytes(login.getSalt()),
                    this.getName());
        }
        return null;
    }

    // 用来做授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进入授权");
        // 获取主身份信息
        LoginVo login = (LoginVo) principals.getPrimaryPrincipal();

        // 获取角色信息
        List<TbRole> userRoles = loginService.findUserRoles(login.getUserId());
        //用户角色列表
        HashSet<String> roles = new HashSet<String>();
        if (userRoles != null && userRoles.size() != 0) {
			//把角色放入集合，用来添加权限
			userRoles.forEach(role -> roles.add(role.getRoleName()));
		}

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }
}
